package view;

import entity.*;
import service.*;
import util.DateUtil;
import util.IDGenerator;
import util.LogUtil;

import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class CounterStaffView {
    private Scanner scanner = new Scanner(System.in);
    private IMovieService movieService = new MovieServiceImpl();
    private IScheduleService scheduleService = new ScheduleServiceImpl();
    private ITicketService ticketService = new TicketServiceImpl();
    private User currentUser;

    public void showCounterStaffView(User user) {
        currentUser = user;
        while (true) {
            System.out.println("===== 前台界面 =====");
            System.out.println("1. 列出正在上映影片");
            System.out.println("2. 列出场次信息");
            System.out.println("3. 列出指定电影和场次的座位信息");
            System.out.println("4. 售票");
            System.out.println("5. 退票");
            System.out.println("6. 修改密码");
            System.out.println("7. 退出登录");
            System.out.print("请选择操作：");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    listCurrentMovies();
                    break;
                case "2":
                    listSchedules();
                    break;
                case "3":
                    listSeatInformation();
                    break;
                case "4":
                    sellTicket();
                    break;
                case "5":
                    refundTicket();
                    break;
                case "6":
                    modifyPassword();
                    break;
                case "7":
                    System.out.println("退出登录！");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入！");
            }
        }
    }

    private void listCurrentMovies() {
        List<Movie> movies = movieService.getAllMovies();
        System.out.println("===== 正在上映影片 =====");
        System.out.println("影片 ID\t影片名称\t导演\t主演\t评分");
        for (Movie movie : movies) {
            System.out.println(movie.getMovieId() + "\t" + movie.getName() + "\t" +
                    movie.getDirector() + "\t" + movie.getStars() + "\t" + movie.getRating());
        }
    }

    private void listSchedules() {
        System.out.print("请输入日期（格式：yyyy-MM-dd，留空则显示最近一周场次）：");
        String dateStr = scanner.nextLine();
        Date date = null;
        if (!dateStr.isEmpty()) {
            date = DateUtil.parseDate(dateStr + " 00:00:00");
        } else {
            date = new Date();
            long diffInMillis = 7 * 24 * 60 * 60 * 1000;
            Date endDate = new Date(date.getTime() + diffInMillis);
            List<Schedule> schedules = scheduleService.getAllSchedules();
            System.out.println("===== 最近一周场次 =====");
            System.out.println("场次 ID\t影片名称\t放映厅\t开始时间\t\t\t票价");
            for (Schedule schedule : schedules) {
                if (schedule.getStartTime().after(date) && schedule.getStartTime().before(endDate)) {
                    System.out.println(schedule.getScheduleId() + "\t" + schedule.getMovie().getName() + "\t" +
                            schedule.getCinemaHall().getHallName() + "\t" + DateUtil.formatDate(schedule.getStartTime()) + "\t" + schedule.getPrice());
                }
            }
            return;
        }

        List<Schedule> schedules = scheduleService.getSchedulesByDate(date);
        System.out.println("===== 场次列表 =====");
        System.out.println("场次 ID\t影片名称\t放映厅\t开始时间\t\t\t票价");
        for (Schedule schedule : schedules) {
            System.out.println(schedule.getScheduleId() + "\t" + schedule.getMovie().getName() + "\t" +
                    schedule.getCinemaHall().getHallName() + "\t" + DateUtil.formatDate(schedule.getStartTime()) + "\t" + schedule.getPrice());
        }
    }

    private void listSeatInformation() {
        System.out.print("请输入影片 ID：");
        String movieId = scanner.nextLine();
        Movie movie = movieService.getMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.print("请输入场次 ID：");
        String scheduleId = scanner.nextLine();
        Schedule schedule = scheduleService.getScheduleById(scheduleId);
        if (schedule == null || !schedule.getMovie().getMovieId().equals(movieId)) {
            System.out.println("场次不存在或与影片不匹配！");
            return;
        }

        CinemaHall hall = schedule.getCinemaHall();
        int rows = hall.getRows();
        int seatsPerRow = hall.getSeatsPerRow();

        System.out.println("===== 座位信息 =====");
        System.out.print("   ");
        for (int i = 1; i <= seatsPerRow; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        for (int i = 1; i <= rows; i++) {
            System.out.print(i + "  ");
            for (int j = 1; j <= seatsPerRow; j++) {
                boolean isSold = false;
                for (Ticket ticket : ticketService.getTicketsByScheduleId(scheduleId)) {
                    if (ticket.getSeatRow().equals(String.valueOf(i)) && ticket.getSeatNumber() == j && ticket.getStatus().equals("已售出")) {
                        isSold = true;
                        break;
                    }
                }
                System.out.print((isSold ? "X " : "O ") + (j == seatsPerRow ? "" : ""));
            }
            System.out.println();
        }
    }

    private void sellTicket() {
        System.out.print("请输入场次 ID：");
        String scheduleId = scanner.nextLine();
        Schedule schedule = scheduleService.getScheduleById(scheduleId);
        if (schedule == null) {
            System.out.println("场次不存在！");
            return;
        }

        CinemaHall hall = schedule.getCinemaHall();
        int rows = hall.getRows();
        int seatsPerRow = hall.getSeatsPerRow();

        System.out.println("===== 选座 =====");
        System.out.print("请输入座位行（1-" + rows + "）：");
        int seatRow = Integer.parseInt(scanner.nextLine());
        if (seatRow < 1 || seatRow > rows) {
            System.out.println("无效的座位行！");
            return;
        }

        System.out.print("请输入座位号（1-" + seatsPerRow + "）：");
        int seatNumber = Integer.parseInt(scanner.nextLine());
        if (seatNumber < 1 || seatNumber > seatsPerRow) {
            System.out.println("无效的座位号！");
            return;
        }

        boolean isSold = false;
        for (Ticket ticket : ticketService.getTicketsByScheduleId(scheduleId)) {
            if (ticket.getSeatRow().equals(String.valueOf(seatRow)) && ticket.getSeatNumber() == seatNumber && ticket.getStatus().equals("已售出")) {
                isSold = true;
                break;
            }
        }
        if (isSold) {
            System.out.println("该座位已被售出！");
            return;
        }

        Ticket ticket = new Ticket(
                IDGenerator.generateTicketId(),
                schedule,
                String.valueOf(seatRow),
                seatNumber,
                schedule.getPrice()
        );

        boolean result = ticketService.sellTicket(ticket);
        if (result) {
            LogUtil.log("INFO", "售票成功，电子票号：" + ticket.getElectronicTicketId(), currentUser.getUsername());
            System.out.println("售票成功！");
            System.out.println("电子票号：" + ticket.getElectronicTicketId());
            System.out.println("影片：" + schedule.getMovie().getName());
            System.out.println("场次：" + schedule.getScheduleId());
            System.out.println("座位：" + seatRow + " 排 " + seatNumber + " 号");
            System.out.println("票价：" + schedule.getPrice());
        } else {
            System.out.println("售票失败！");
        }
    }

    private void refundTicket() {
        System.out.print("请输入电子票号：");
        String electronicTicketId = scanner.nextLine();

        boolean result = ticketService.refundTicket(electronicTicketId);
        if (result) {
            LogUtil.log("INFO", "退票成功，电子票号：" + electronicTicketId, currentUser.getUsername());
            System.out.println("退票成功！");
        } else {
            System.out.println("退票失败！");
        }
    }

    private void modifyPassword() {
        System.out.print("请输入旧密码：");
        String oldPassword = scanner.nextLine();
        System.out.print("请输入新密码：");
        String newPassword = scanner.nextLine();
        System.out.print("请再次输入新密码：");
        String confirmPassword = scanner.nextLine();

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的新密码不一致！");
            return;
        }

        System.out.println("修改密码功能暂未完全实现！");
    }
}